package com.learn.excel.core.common.serializer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.lang.Nullable;

import java.io.*;

/**
 * @author anri
 * @date 2020/9/30 11:30
 */
@Slf4j
public class BytesRedisSerializer<T> implements RedisSerializer<T> {
    @Nullable
    @Override
    public byte[] serialize(@Nullable T t) throws SerializationException {
        ByteArrayOutputStream byteArrayOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(t);

            byte[] bytes = byteArrayOutputStream.toByteArray();
            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                objectOutputStream.close();
                byteArrayOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new byte[0];
    }

    @Nullable
    @Override
    public T deserialize(@Nullable byte[] bytes) throws SerializationException {
        if(bytes ==null || bytes.length==0){
            return null;
        }
        InputStream inputstream = null;
        ObjectInputStream objectInputStream = null;
        try {
            inputstream = new ByteArrayInputStream(bytes);
            objectInputStream = new ObjectInputStream(inputstream);
            Object o = objectInputStream.readObject();
            T t = (T) o;
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                objectInputStream.close();
                inputstream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
